let start = 1;
let pageSize = 10;

//加载role数据
function load_inti_info() {
    $.get({
        url: '/admin/adminPageInitLoad',
        success: function (result) {
            if (result.status === 200) {
                package_inti_info(result.data);
            }
        }
    })
}

//加载所有部门
function load_department_info(target) {
    $.get({
        url: '/admin/getAllDepartment',
        success: function (result) {
            if (result.status === 200) {
                package_department_info(result.data, target);
            }
        }
    })
}

//加载所以职位信息
function load_role_info(target) {
    $.get({
        url: '/admin/getAllRole',
        success: function (result) {
            if (result.status === 200) {
                package_role_info(result.data, target);
            }
        }
    })
}

//加载角色和部门信息
function package_inti_info(data) {
    let role = $('div.role-menu');
    let department = $('div.department-menu');
    package_role_info(data.roles, role);
    package_department_info(data.departments, department);
}

function package_role_info(data, target) {
    target.empty();
    $.each(data, function (index, item) {
        target.append("<div class='item' data-value='" + item.roleId + "'><span>" + item.roleName + "</span></div>");
    });
}

function package_department_info(data, target) {
    target.empty();
    $.each(data, function (index, item) {
        target.append("<div class='item' data-value='" + item.departmentId + "'><span>" + item.departmentName + "</span></div>");
    })
}

//显示用户添加modal
$('a.left-item.addUser').click(function () {
    $(".ui.modal.user").modal({
        closable: false
    }).modal("show");
    load_inti_info();
    $('#addUser-btn').removeClass('disabled');
});

$('.ui.user.reset.button').click(function () {
    $('#user-form').form('reset');
});
//添加用户表单验证
$('#user-form').form({
    inline: true,
    on: 'blur',
    keyboardShortcuts: false,
    fields: {
        name: {
            identifier: 'name',
            rules: [
                {
                    type: 'empty',
                    prompt: '请输入姓名'
                }
            ]
        },
        role: {
            identifier: 'role',
            rules: [
                {
                    type: 'empty',
                    prompt: '请为选择角色'
                }
            ]
        },
        department: {
            identifier: 'department',
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择部门'
                }
            ]
        },
        username: {
            identifier: 'username',
            rules: [
                {
                    type: 'empty',
                    prompt: '请输入用户名'
                }
            ]
        },
        email:{
            identifier: 'email',
            rules: [
                {
                    type: 'empty',
                    prompt: '请输入邮箱'
                },
                {
                    type: 'regExp',
                    value: /^(\w+)([.]\w+)@timevary.com$/,
                    prompt: "邮箱格式错误"
                }
            ]
        }
    },
    onSuccess: function () {
        let target = $('#addUser-btn');
        addUser(target);
    }
});

//添加新用户
function addUser(target) {
    console.log("添加用户")
    $.post({
        url: '/admin/addUser',
        contentType: "application/json",
        data: JSON.stringify({
            "name": $('#name').val().trim(),
            "roleId": $('#role').val(),
            "username": $('#username').val().trim(),
            "departmentId": $('#department').val(),
            "email": $('#email').val().trim()
        }),
        success: function (result) {
            if (result.status === 200) {
                $(".ui.modal.user").modal('hide');
                $('#user-form').form('clear');
                success(result.msg);
                load_user_info(start, pageSize, 1);
            } else {
                target.removeClass("disabled");
            }
        }
    })
}

$('a.left-item.addRole').click(function () {
    $(".ui.modal.role").modal({
        closable: false
    }).modal("show");
    $("#addRole-btn").removeClass('disabled');
    load_department_info($('.department-menu-role'));
});
$('.ui.role.reset.button').click(function () {
    $('#role-form').form('reset');
});

$('#position-department').change(function () {
    let departmentId = $(this).val();
    if (!check_number(departmentId)) {
        return;
    }
    $.get({
        url: '/admin/getPermissionUnderTheDepartment',
        data: {
            "departmentId": departmentId
        },
        success: function (result) {
            if (result.status === 200) {
                $('#permission-select').removeClass('disabled');
                let target = $('#permission-menu');
                package_permission_menu(result.data, target);
            }
        }
    })
})

function package_permission_menu(data, target) {
    target.empty();
    $.each(data, function (index, item) {
        target.append("<div class='item' data-value='" + item.permissionId + "'><span>" + item.permissionName + "</span></div>");
    });
}

$('#role-form').form({
    inline: true,
    on: 'blur',
    keyboardShortcuts: false,
    fields: {
        position: {
            identifier: 'position',
            rules: [
                {
                    type: 'empty',
                    prompt: '请输入职位名称'
                }
            ]
        },
        permission: {
            identifier: "permission",
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择权限'
                }
            ]
        },
        department: {
            identifier: "position-department",
            rules: [
                {
                    type: 'empty',
                    prompt: '请选择部门'
                }
            ]
        }
    },
    onSuccess: function () {
        add_role();
    }
});

function add_role() {
    $("#addRole-btn").addClass('disabled');
    let permissionIds = $('#permission').val().split(",");
    $.post({
        url: '/admin/addNewPosition',
        data: {
            "roleName": $('#position').val(),
            "permissionIds": permissionIds,
            "departmentId": $('#position-department').val()
        },
        success: function (result) {
            if (result.status === 200) {
                $('#role-form').form("reset");
                $('.ui.modal.role').modal("hide");
                success(result.msg);
            }
        }
    })
}

$('a.left-item.addDepartment').click(function () {
    $(".ui.modal.department").modal({
        closable: false
    }).modal("show");
    $("#addDepartment-btn").removeClass('disabled');
});
$('.ui.department.reset.button').click(function () {
    $('#department-form').form('reset');
});

$('#department-form').form({
    inline: true,
    on: 'blur',
    keyboardShortcuts: false,
    fields: {
        newDepartment: {
            identifier: 'newDepartment',
            rules: [
                {
                    type: 'empty',
                    prompt: '请输入部门名称'
                }
            ]
        }
    },
    onSuccess: function () {
        add_department();
    }
});

function add_department() {
    failure('暂未开放');
    // $.post({})
}

let ds = $('#admin-description');
//员工管理
$('a.item.staff-management').click(function () {
    let cur = $('#user');
    if (cur.hasClass('hide')) {
        load_user_info(start, pageSize, 1);
        cur.toggleClass('hide');
        ds.hide(300);
    } else {
        ds.show(300);
        cur.toggleClass('hide');
    }
})

//获取用户信息
function load_user_info(start, pageSize, value) {
    $.get({
        url: '/admin/getAllUser',
        data: {
            "pageNum": start,
            "pageSize": pageSize
        },
        success: function (result) {
            if (result.status === 200) {
                package_user_info(result.data);
                renderTfoot(pageSize, result.data, 'load_user_info', 1, start);
                load_inti_info();
                load_department_info($('.department-menu-my'));
            }
        }
    })
}

//封装用户tbody
function package_user_info(data) {
    let list = data.list;
    let content = "";
    for (let i = 0; i < list.length; i++) {
        content += "<tr>" +
            "<td class='ds'><input type='checkbox' name='checkIt' class='hide'></td>" +
            "<td class='ds disabled'>" + parseInt(i + 1) + "</td>" +
            "<td>" + list[i].username + "</td>" +
            // "<td  class='ds' data-tooltip='"+list[i].password+"' data-position='top center'><div class='remarks'>" + list[i].password + "</div></td>" +
            "<td class='ds'>" + list[i].createTime + "</td>" +
            "<td>" + list[i].name + "</td>" +
            "<td class=\"department disabled\">\n" +
            "                <div class=\"ui inline dropdown\">\n" +
            "                    <input type=\"hidden\" class='department-text'>\n" +
            "                    <div class=\"default text\"><span>" + list[i].department + "</span></div>\n" +
            "                    <i class=\"dropdown icon\"></i>\n" +
            "                    <div class=\"menu department-menu-my\">\n" +
            "                    </div>\n" +
            "                </div>\n" +
            "            </td>" +
            "<td class=\"role disabled\">\n" +
            "                <div class=\"ui inline dropdown\">\n" +
            "                    <input type=\"hidden\" class='role-text'>\n" +
            "                    <div class=\"default text\"><span>" + list[i].role + "</span></div>\n" +
            "                    <i class=\"dropdown icon\"></i>\n" +
            "                    <div class=\"menu role-menu-after\">\n" +
            "                    </div>\n" +
            "                </div>\n" +
            "            </td>" +
            "<td class='ds'>" + list[i].timeOnline + "</td>" +
            "<td class='ds status'>" + list[i].userStatus + "</td>" +
            "<td class='ds operation'>" +
            "<div class=\"ui  horizontal link list\">" +
            "<div class='item'>" +
            "<button class=\"ui positive animated button edit-button\">\n" +
            "                                <div class=\"visible content\">编辑</div>\n" +
            "                                <div class='hidden content'>\n" +
            "                                    <i class='edit outline icon'></i>\n" +
            "                                </div>\n" +
            "</button>\n" +
            "</div>" +
            "<div class='item'>" +
            "                            <button class=\"ui olive animated button cancel-button disabled\">\n" +
            "                                <div class=\"visible content\">取消</div>\n" +
            "                                <div class=\"hidden content\">\n" +
            "                                    <i class=\"reply icon\"></i>\n" +
            "                                </div>\n" +
            "                            </button>\n" +
            "</div>" +
            "<div class='item'>" +
            "                            <button class='ui primary animated button save-button disabled' data-value='" + list[i].userUuid + "'>\n" +
            "                                <div class='visible content'>保存</div>\n" +
            "                                <div class=\"hidden content\">\n" +
            "                                    <i class=\"save outline icon\"></i>\n" +
            "                                </div></button>\n" +
            "</div>" +
            "<div class='item'>" +
            "                <div class='ui dropdown item'>\n" +
            "                    More\n" +
            "                    <i class='dropdown icon'></i>\n" +
            "                    <div class='menu'>\n" +
            "                        <a class='item delete-button' data-value='" + list[i].userUuid + "'><i class='trash alternate icon'></i>删除</a>\n" +
            "                        <a class='item reset-password' data-value='" + list[i].userUuid + "'><i class='reply icon'></i>重置密码</a>\n" +
            "                        <a class='item disabled-user' data-value='" + list[i].userUuid + "'><i class='frown icon'></i>禁用</a>\n" +
            "                        <a class='item unlock-user' data-value='" + list[i].userUuid + "'><i class='frown outline icon'></i>解封</a>\n" +
            "                    </div>\n" +
            "                </div>\n" +
            " </div>" +
            // "                            </button>" +
            // "                            <button class='ui primary animated button delete-button' data-value='" + list[i].userUuid + "'>\n" +
            // "                                <div class='visible content'>删除</div>\n" +
            // "                                <div class='hidden content'>\n" +
            // "                                    <i class='trash alternate icon'></i>\n" +
            // "                                </div>\n" +
            // "                            </button>" +
            // "                            <button class='ui positive animated button reset-password' data-value='" + list[i].userUuid + "'>\n" +
            // "                                <div class='visible content'>重置密码</div>\n" +
            // "                                <div class='hidden content'>\n" +
            // "                                    <i class='reply icon'></i>\n" +
            // "                                </div>\n" +
            // "                            </button>" +
            "</td>" +
            "</tr>"
    }
    $('tbody').html(content);
    $('#total').html("共" + data.pages + "页 " + data.total + " 条记录" + "&nbsp;&nbsp;当前页: " + data.pageNum);
    $('.ui.dropdown').dropdown({
        on: 'hover'
    });
}

let content;
//编辑工单
$(document).on("click", ".edit-button", function () {
    content = admin_open_edit($(this));
    let curtd = $(this).parent().parent().parent();
    curtd.siblings('.role').removeClass('disabled');
    curtd.siblings('.department').removeClass('disabled');
    $('.ui.inline.dropdown').dropdown({
        on: 'click'
    });
})


$(document).on('change', '.department-text', function () {
    let departmentId = $(this).val();
    let role = $(this).parent().parent().parent().children('.role');
    let target = role.find('.role-menu-after');
    $.get({
        url: '/admin/getAPositionUnderTheDepartment',
        data: {
            "departmentId": departmentId
        },
        success: function (result) {
            if (result.status === 200) {
                package_role_info(result.data, target);
                let input = role.find('.role-text');
                let default_text = role.find('.text');
                let first = target.children().first();
                input.val(first.attr('data-value'));
                default_text.html(first.html());
            }
        }
    })
})


//取消修改
$(document).on("click", ".cancel-button", function () {
    admin_close_edit(content, $(this));
});
//保存
$(document).on("click", ".save-button", function () {
    let td = $(this).parent().parent().parent();
    let data = td.siblings().not(".ds");
    let tr = td.parent();
    td.siblings('.role').addClass('disabled');
    td.siblings('.department').addClass('disabled');
    $(this).toggleClass('disabled').parent().parent().siblings().children().toggleClass('disabled');
    update_user_info(data, tr, $(this).attr('data-value'));
});


function update_user_info(data, tr, id) {
    let role = tr.find('.role-text').val();
    let department = tr.find('.department-text').val();
    $('.edit-button').removeClass('disabled');
    if (!verify_number(role) || !verify_number(department)) {
        failure("请选择部门");
        return;
    }
    console.log(department + role);
    $.post({
        url: '/admin/modifyUserInfo',
        contentType: "application/json",
        data: JSON.stringify({
            "userUuid": id,
            "username": data[0].innerText,
            "name": data[1].innerText,
            "departmentId": department,
            "roleId": role
        }),
        success: function (result) {
            switch (result.status) {
                case 200:
                    data.removeAttr('contenteditable');
                    success(result.msg);
                    break;
                default:
                    tr.replaceWith(content);
                    failure(result.msg);
            }
        }
    })
}

//删除
$(document).on("click", ".delete-button", function () {
    let target = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要删除?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        delete_user(target);
        layer.close(index);
    });

});

//重置密码
$(document).on("click", ".reset-password", function () {
    let target = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要重置吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        reset_password(target);
        layer.close(index);
    });
});

function reset_password(target) {
    let userUuid = $(target).attr('data-value');
    if (!reg.test(userUuid)) {
        failure("删除失败")
        return;
    }
    $.get({
        url: '/admin/resetPassword',
        data: {
            "userId": userUuid
        },
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
            }
        }
    })
}

//禁用用户
$(document).on("click", ".disabled-user", function () {
    let target = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要禁用该用户吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        disable_user(target);
        layer.close(index);
    });
});

function disable_user(target) {
    let userUuid = $(target).attr('data-value');
    if (!reg.test(userUuid)) {
        failure("操作失败")
        return;
    }
    $.get({
        url: '/admin/disableUser',
        data: {
            "userId": userUuid
        },
        success: function (result) {
            if (result.status === 200) {
                target.parents('.operation').siblings('.status').text(result.data)
                success(result.msg);
            }
        }
    })
}

//解封用户
$(document).on("click", ".unlock-user", function () {
    let target = $(this);
    $('.layui-layer-btn0').removeClass('end');
    layer.confirm('确定要解封该用户吗?', {
        btn: ['确定', '取消'],
        icon: 3,
        title: '提示',
        shade: [0.6, '#ffffff', true]
    }, function (index) {
        $('.layui-layer-btn0').addClass('end');
        unlock_user(target);
        layer.close(index);
    });
});

function unlock_user(target) {
    let userUuid = $(target).attr('data-value');
    if (!reg.test(userUuid)) {
        failure("操作失败")
        return;
    }
    $.get({
        url: '/admin/unLockUser',
        data: {
            "userId": userUuid
        },
        success: function (result) {
            if (result.status === 200) {
                target.parents('.operation').siblings('.status').text(result.data)
                success(result.msg);
            }
        }
    })
}


let reg = new RegExp("[a-z0-9]{32}");

function delete_user(target) {
    let userUuid = $(target).attr('data-value');
    console.log(userUuid);
    if (!reg.test(userUuid)) {
        failure("删除失败")
        return;
    }
    $.get({
        url: '/admin/deleteUsers',
        data: {
            "userUuid": userUuid
        },
        success: function (result) {
            if (result.status === 200) {
                //删除当前行
                $(target).parent().parent().remove();
                success(result.msg);
            }
        }
    })
}

//刷新
$('#reload-user').click(function () {
    if (flag) {
        flag = false;
        let default_role = $('#role-text');
        let default_department = $('#department-text');
        if (!default_role.hasClass("default")) {
            $('#role-search').val("");
            default_role.html("请选择职位").addClass('default');
        }
        if (!default_department.hasClass("default")) {
            $('#department-search').val("");
            default_department.html("请选择部门").addClass('default');
        }
        load_user_info(start, pageSize, 1);
        load_department_info($('.department-menu-my'));
        flag = true;
    }
})

//查询按钮
$('.ui.button.search-user').click(function () {
    if (flag) {
        flag = false;
        let searchValue = $('#search-text').val().trim();
        if (/^([a-zA-Z0-9.\u4E00-\u9FA5]+)$/.test(searchValue)) {
            console.log("查询")
            query_user(start, pageSize, searchValue);
        } else {
            failure("非法字符");
        }
        flag = true;
    }
});

//文本框查询用户
function query_user(start, pageSize, searchValue) {
    $.get({
        url: '/admin/multiConditionQueryUser',
        data: {
            "pageNum": start,
            "pageSize": pageSize,
            "searchValue": searchValue
        },
        success: function (result) {
            if (result.status === 200) {
                package_user_info(result.data);
                load_department_info($('.department-menu-my'));
                renderTfoot(pageSize, result.data, 'query_user', searchValue, start);
            }
        }
    })
}

$('#role-search').change(function () {
    query_user_by_role(start, pageSize, $(this).val());
});

$('#department-search').change(function () {
    query_user_by_department(start, pageSize, $(this).val());
});

//职位下拉框查询用户
function query_user_by_role(start, pageSize, role) {
    $.get({
        url: '/admin/queryUserInformationByRole',
        data: {
            "pageNum": start,
            "pageSize": pageSize,
            "roleId": role
        },
        success: function (result) {
            if (result.status === 200) {
                package_user_info(result.data);
                load_department_info($('.department-menu-my'));
                renderTfoot(pageSize, result.data, 'query_user_by_role', role, start);
            }
        }
    })
}

//部门下拉框查询用户
function query_user_by_department(start, pageSize, department) {
    $.get({
        url: '/admin/queryUserInformationByDepartment',
        data: {
            "pageNum": start,
            "pageSize": pageSize,
            "departmentId": department
        },
        success: function (result) {
            if (result.status === 200) {
                package_user_info(result.data);
                load_department_info($('.department-menu-my'));
                renderTfoot(pageSize, result.data, 'query_user_by_department', department, start);
            }
        }
    })
}

$('.ui.del-role.reset.button').click(function () {
    $('#delete-role-form').form('reset');
});

$('a.item.left-item.delete-role-info').click(function () {
    $('.ui.modal.delete-role-modal').modal({
        closable: false
    }).modal("show");
    load_role_info($('.delete-role-menu'));
    $('#deleteRole-btn').removeClass("disabled");
});

$('#delete-role-form').form({
    inline: false,
    on: "submit",
    keyboardShortcuts: false,
    fields: {
        role_info: {
            identifier: "delete-role-info",
            rules: [
                {
                    type: "empty",
                    prompt: "请选择要删除的职位"
                }
            ]
        }
    },
    onSuccess: function () {
        let target = $('#deleteRole-btn');
        target.addClass("disabled");
        del_role_info(target);
    }
})

function del_role_info(target) {
    let roleId = $('#delete-role-info').val();
    if (!verify_number(roleId)) {
        failure("禁止篡改数据");
        target.removeClass("disabled");
        return;
    }
    $.get({
        url: '/admin/deleteRoleInfo',
        data: {
            "roleId": roleId
        },
        success: function (result) {
            if (result.status === 200) {
                success(result.msg);
                $('.delete-role-modal').modal("hide")
            } else {
                target.removeClass("disabled");
            }
        }
    })
}